import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import kill from 'tree-kill';

const execAsync = promisify(exec);
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export interface ProcessInfo {
    pid: number;
    name: string;
}

/**
 * 获取所有正在运行的 Cursor 进程。
 * @returns 返回一个包含进程信息的数组。
 */
export async function getCursorProcesses(): Promise<ProcessInfo[]> {
    const command = process.platform === 'win32'
        ? `tasklist /fo csv /nh /fi "imagename eq cursor.exe"`
        : `ps -ax | grep -i "[C]ursor"`;

    try {
        const { stdout } = await execAsync(command);
        if (!stdout.trim()) {
            return [];
        }

        if (process.platform === 'win32') {
            return stdout.trim().split('\n').map(line => {
                if (!line) return null;
                const parts = line.split('","');
                if (parts.length < 2) return null;
                const name = parts[0].replace(/"/g, '');
                const pid = parseInt(parts[1].replace(/"/g, ''), 10);
                return { name, pid };
            }).filter((p): p is ProcessInfo => p !== null && !isNaN(p.pid));
        } else {
            return stdout.trim().split('\n').map(line => {
                if (!line) return null;
                const parts = line.trim().split(/\s+/);
                const pid = parseInt(parts[0], 10);
                const name = parts.slice(4).join(' ');
                return { name, pid };
            }).filter((p): p is ProcessInfo => p !== null && !isNaN(p.pid));
        }
    } catch (error) {
        return [];
    }
}

/**
 * 温和或强制地关闭指定的进程树。
 * 使用 'tree-kill' 库确保跨平台兼容性和可靠性。
 * @param pids - 要终止的父进程 PID 列表。
 * @param options - 配置选项，包括超时时间和是否强制。
 * @returns 一个包含操作成功状态和描述性消息的对象。
 */
export async function quitCursorProcesses(
    pids: number[], 
    options: { timeout?: number; force?: boolean } = {}
): Promise<{ success: boolean; message: string }> {
    if (pids.length === 0) {
        return { success: true, message: '没有需要关闭的进程。' };
    }

    const { timeout = 5, force = false } = options;
    const signal = force ? 'SIGKILL' : 'SIGTERM';

    // 使用 tree-kill 终止所有找到的进程树
    const killPromises = pids.map(pid => new Promise<void>((resolve) => {
        kill(pid, signal, (err) => {
            if (err) {
                // 如果进程已不存在，也视为成功
                console.warn(`Warning: Failed to kill process ${pid} with signal ${signal}. It might have already exited.`, err);
            }
            resolve();
        });
    }));

    await Promise.all(killPromises);
    
    // 等待并验证进程是否已全部退出
    const startTime = Date.now();
    while (Date.now() - startTime < timeout * 1000) {
        const remainingProcesses = await getCursorProcesses();
        if (remainingProcesses.length === 0) {
            return { success: true, message: '成功关闭所有 Cursor 进程。' };
        }
        await sleep(100); // 缩短验证间隔以加快响应
    }

    const finalList = await getCursorProcesses();
    if (finalList.length > 0) {
        const processList = finalList.map(p => p.pid).join(', ');
        return {
            success: false,
            message: `关闭超时。以下进程未能退出: ${processList}`
        };
    }
    
    return { success: true, message: '成功关闭所有 Cursor 进程。' };
} 